<?php
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM news WHERE id = '$id'");
$queryTwo = mysql_query("SELECT * FROM comments WHERE newid = '$id' ORDER BY id asc");
if ($_POST['addcomment'])
{
	$bodyF = mysql_real_escape_string($_POST['body']);
	$nameF = mysql_real_escape_string($_POST['name']);
	$body = strip_tags($bodyF);
	$name = strip_tags($nameF);
	$ip = $_SERVER['REMOTE_ADDR'];
	if($ip == '::1')
		$ip = 'localhost';
	if(!$name)
		$name = 'Anonymous';
	if(!$body)
		$main = 'You have to atleast write in something!';
	else {
		$date = date("y-m-d");
		mysql_query("INSERT INTO `comments` (`newid`, `body`, `date`, `by`, `ip`) VALUES ('$id', '$body', '$date', '$name', '$ip')");

		mysql_query("UPDATE news SET comments = comments + 1 WHERE id = '$id'");
		header("Location: ?page=comments&id=$id");
		exit;
	}
}
$deleteID = $_GET['delete'];
if ($_GET['delete']) {
	if($check->isAdmin()) {
		mysql_query("DELETE FROM comments WHERE id = '$deleteID'");
		mysql_query("UPDATE news SET comments = comments - 1 WHERE id = '$id'");
		header("Location: ?page=comments&id=$id");
		exit;
	} else {
		$main .= 'You\'re not admin, you can\'t delete comments.';
	}
}
if(!$id) $main = '<h2>Correct usage: ?page=comments&id=ID_HERE</h2>';
if(mysql_num_rows($query) < 1)
	$main .= '<h2>ID '.$id.' not found.</h2>';
else {
	while ($row = mysql_fetch_assoc($query))
	{
		$main .= '<h2>Comments - '.$row['title'].'</h2>';
	}
	if(mysql_num_rows($queryTwo) < 1)
		$main .= 'No comments found';
	else 
		while ($row = mysql_fetch_assoc($queryTwo))
		{
			$main .= '
			'.$row['body'].'
					
			<p class="post-footer align-right">					
			<a href="#" class="readmore">Posted by '.$row['by'].'</a>
			<span class="date">'.$row['date'].'</span>
			';if($check->isAdmin()) {
			$main .= '
			IP: '.$row['ip'].' 
			<a href="?page=comments&id='.$id.'&delete='.$row['id'].'">[DELETE]</a>'; } $main .= '
			</p>
			';
			
		}
	$main .= '		
		<h2>Post comment</h2>
		<table cellpadding="4" cellspacing="1" width="100%">
			<tr>
				<td>
					'.$result.'
					<form method="post" name="addcomment" action="?page=comments&id='.$id.'">
					<b>Name:</b><br />
					<input type="text" name="name" />
					<br />
					<b>Body:</b><br />
					<textarea name="body" cols="100" rows="6" onkeypress="javascript:return (this.value.length < 4096)"></textarea>
					<br />
					<input type="submit" value="Submit" name="addcomment" />
					</form>
				</td>
			</tr>
		</table>';
}
?>